<?php

/**
 * 用于 未做分库分表但 需要做主从的情况
 */
class CDbConnectionExt_v3 extends CDbConnectionMasterSlave {
	/**
	 * 从库配置
	 */
	public $slaves = array();
	
	/**
	 * 当前的从库连接
	 * @var CDbConnection
	 */
	private $_slave = null;

	/**
	 * 获取一个从库链接.
	 * @return CDbConnection
	 */
	public function getSlave() {
		if($this->_slave === null) {
			if(empty($this->slaves)) return $this;
			
			$keys = array_keys($this->slaves);
			shuffle($keys);
			$key = array_shift($keys);
			$config = $this->slaves[$key];
			
			Yii::trace("Opened slave DB: {$config['connectionString']}", __METHOD__.':'.__LINE__);
			$this->_slave = new CDbConnectionMasterSlave($config['connectionString'], $config['username'], $config['password']);
			$this->_slave->enableSlave = false;

			!$this->_slave && $this->_slave = $this;
		}
		return $this->_slave;
	}
}
